import 'package:flutter_admin/api/odoo/stock_quant_odoo_api.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/models/odoo/stock_quant.dart';
import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/pages/odoo/material/workshop_picking/batch_out.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:intl/intl.dart';

import 'batch_return_products.dart';

class ProductOdoData extends StatefulWidget {

  final bool isReturn;
  ProductOdoData({Key? key,this.isReturn = false}) : super(key: key);
  @override
  _ProductOdoDataState createState() =>
      _ProductOdoDataState();
}

class _ProductOdoDataState extends State<ProductOdoData> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  StockQuant stockQuant = StockQuant();
  //工厂名称
  List<SelectOptionVO> locationIdList = [];
  //车间名称
  List<SelectOptionVO> workshopIdList = [];

  DateFormat format= DateFormat('yyyy-MM-dd');

  UserInfo userInfo = StoreUtil.getCurrentUserInfo();

  List dataList = [];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      // _query();
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    if (userInfo.major != null) {
      this.workshopIdList = await DynamicDataApi.getModelSelect(
        // active: false,
          model: "hr.department",
          name: "complete_name",
          key: 'parent_id',
          operator: "!=",
          val: null);
    } else {
      locationIdList = await DynamicDataApi.getModelSelect(
          active: false,
          model: "stock.location",
          name: "complete_name",
          key: 'workshop_id',
          val: int.parse(userInfo.deptId!),
          key2: 'comment',
          val2: 'XBK');
      stockQuant.workshopId = userInfo.deptId;
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          userInfo.major != null
              ? CrySelect(
            width: 280,
            label: '生产车间',
            dataList: workshopIdList,
            value: stockQuant.workshopId,
            onSaved: (v) => {stockQuant.workshopId = v},
            onChange: (v) async {
              if (stockQuant.workshopId != v) {
                formKey.currentState!.save();
                stockQuant.workshopId = v;
                stockQuant.locationId = null;
                try {
                  locationIdList = await DynamicDataApi.getModelSelect(
                      active: false,
                      model: "stock.location",
                      name: "complete_name",
                      key: 'workshop_id',
                      val: int.parse(v),
                      key2: 'comment',
                      val2: 'XBK');
                } catch (e) {
                  locationIdList = [];
                }
                setState(() {});
              }
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          )
              : CryInput(
            width: 200,
            label: '生产车间',
            enable: false,
            value: userInfo.deptName,
          ),
          CrySelect(
            label: '库房',
            width: 380,
            dataList: locationIdList,
            value: stockQuant.locationId,
            onSaved: (v) => {stockQuant.locationId = v},
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInput(
            width: 280,
            label: '物料名称',
            value: stockQuant.productName,
            onSaved: (v) {
              stockQuant.productName = v;
            },
          ),
          CryInput(
            width: 280,
            label: '规格型号',
            value: stockQuant.productDes,
            onSaved: (v) {
              stockQuant.productDes = v;
            },
          ),
          Padding(
            padding: EdgeInsets.only(top: 15),
            child: SizedBox(child: CryButtonBar(children: [
              CryButtons.query(context, () => _query()),
              CryButtons.reset(context, () => _reset()),
              widget.isReturn?
              CryButton(
                label: "退货确认",
                iconData: Icons.confirmation_num,
                onPressed: _isSelected()
                    ? () => _batchReturnProducts()
                    : null,):
              CryButton(
                label: "出库确认",
                iconData: Icons.confirmation_num,
                onPressed: _isSelected()
                    ? () => _batchOut()
                    : null,),
            ],)),
          ),
        ],
      ),
    );

    var table = DataTable(
      columns: [
        DataColumn(label: Text('仓库位置')),
        DataColumn(label: Text('物料编号')),
        DataColumn(label: Text("物料名称")),
        DataColumn(label: Text("规格型号")),
        DataColumn(label: Text("数量")),
        DataColumn(label: Text('安全库存数量')),
        DataColumn(label: Text("计量单位")),
      ],
      rows: this.dataList.map((map) {
        var result = DataRow(
            selected: map["selected"],
            onSelectChanged: (selected) {
              setState(() {
                map["selected"] = selected;
              });
            },
            cells: [
              DataCell(Text(map["location"]["name"]!=false?map["location"]["name"].toString():"")),
              DataCell(Text(map["product"]["default_code"]!=false?map["product"]["default_code"].toString():"")),
              DataCell(Text(map["product"]["name"]!=false?map["product"]["name"].toString():"")),
              DataCell(Text(map["product"]["description"]!=false?map["product"]["description"].toString():"")),
              DataCell(Text(map["quantity"]!=false?map["quantity"].toString():"",style: map['stock_status']==0?TextStyle(color: Colors.red):TextStyle(),)),
              DataCell(Text(map["warn_quant"]!=false?map["warn_quant"].toString():"")),
              DataCell(Text(map["uom"]['name']!=false?map["uom"]['name'].toString():"")),
            ]
        );
        return result;
      }).toList(),
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text(widget.isReturn?"批量退货":"批量出库"),
      ),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(height: 10),
            form,
            // buttonBar,
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child:table,
            ),
          ],
        ),
      ),
      // bottomNavigationBar: bottomNavigationBar,
    );
    return result;
  }

  bool _isSelected(){
    for (var i = 0; i < dataList.length; i++) {
      if (dataList[i]["selected"]) return true;
    }
    return false;
  }

  _batchReturnProducts() {
    List<Map<String,dynamic>> list = [];
    dataList.forEach((element) {
      if(element["selected"])
        list.add(element);
    });
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: BatchReturnProducts(
          dataList: list,
          // plancode: plancode
        ),
      ),
    ).then((v) {
      if (v != null) {
        _query();
      }
    });
  }

  _batchOut() {
    List<Map<String,dynamic>> list = [];
    dataList.forEach((element) {
      if(element["selected"])
        list.add(element);
    });
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: BatchOut(
            dataList: list,
            // plancode: plancode
        ),
      ),
    ).then((v) {
      if (v != null) {
        _query();
      }
    });
  }

  _reset() {
    stockQuant = StockQuant();
    formKey.currentState!.reset();
    dataList = [];
    setState(() {});
  }

  _query() {
    formKey.currentState?.save();
    _loadData();
  }

  _loadData() async {
    if (!formKey.currentState!.validate()) {
      return;
    }
    ResponseBodyApi responseBodyApi = await StockQuantOdooApi.productOdoData(
        stockQuant.toProductOdoData());
    if (responseBodyApi.success!) {
      dataList = responseBodyApi.data;
      dataList.forEach((element) {
        element["selected"] = false;
      });
      setState(() {});
    }
  }

}
